package com.csii.ssm.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决前端跨域
 * <p>
 * 参考：https:developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
 * <p>
 * <filter>
 * <display-name>CORSFilter</display-name>
 * <filter-name>CORSFilter</filter-name>
 * <filter-class>com.csii.ssm.filter.CORSFilter</filter-class>
 * <init-param>
 * <param-name>CORSACAO</param-name>
 * <param-value>http:ip:9000</param-value>
 * </init-param>
 * <init-param>
 * <param-name>CORSACMA</param-name>
 * <param-value>3600</param-value>
 * </init-param>
 * </filter>
 * <filter-mapping>
 * <filter-name>CORSFilter</filter-name>
 * <servlet-name>*.do</servlet-name>
 * </filter-mapping>
 *
 * @author zhaojin 15398699939@163.com
 * @create 2016-09-13-15:33
 */

public class CORSFilter implements Filter {

    public static final String CORSACAO = "Access-Control-Allow-Origin";
    public static final String CORSACAC = "Access-Control-Allow-Credentials";
    public static final String CORSACMA = "Access-Control-Max-Age";
    public static final String CORSACAM = "Access-Control-Allow-Methods";
    public static final String CORSACAH = "Access-Control-Allow-Headers";

    //该字段是必须的。它的值要么是请求时Origin字段的值，要么是一个*，表示接受任意域名的请求。
    private String corsacao;
    //该字段可选，用来指定本次预检请求的有效期，单位为秒。如Access-Control-Max-Age: 1728000，有效期是20天（1728000秒），即允许缓存该条回应1728000秒（即20天），在此期间，不用发出另一条预检请求。
    private String corsacma;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.corsacao = filterConfig.getInitParameter("CORSACAO");
        this.corsacma = filterConfig.getInitParameter("CORSACMA");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader(CORSACAO, corsacao);
        httpServletResponse.setHeader(CORSACAC, "true");
        httpServletResponse.setHeader(CORSACAM, "GET,POST,OPTIONS");
        httpServletResponse.setHeader(CORSACAH, "X-Requested-With,Content-Type");
        httpServletResponse.setHeader(CORSACMA, corsacma);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
